package com.jiazhong.controller;

import com.jiazhong.commons.bean.User;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/login_session")
public class LoginSessionController extends HttpServlet {

    private List<User> users = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        User u1 = new User("zhangsan", "123456", "张三");
        User u2 = new User("lisi", "1234567", "李四");
        User u3 = new User("wangwu", "123", "王五");
        User u4 = new User("admin", "111111", "管理员");
        users.add(u1);
        users.add(u2);
        users.add(u3);
        users.add(u4);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 判断登陆是否成功
        boolean flag = false; // 错
        User login = null;
        for (User user : users) {
            if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                flag = true;
                login = user;
                break;
            }
        }
        HttpSession session = request.getSession();
        // 响应
        if (flag) {
            // 1.保存登陆信息
            session.setAttribute("USER", login);
            // 2.跳转
            response.sendRedirect("session/main.jsp");
        } else {
            session.setAttribute("ERROR", "账号或者密码错误");
            response.sendRedirect("session/login.jsp");
        }
    }
}
